package top.healthylife.gateway.mgr.component;

import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import top.healthylife.basics.utils.exception.BusinessException;
import top.healthylife.gateway.mgr.service.GatewayLogService;
import top.heathylife.gateway.common.po.GatewayLogPo;

/**
 * @author : maoxiaomeng
 */
@Component
@Slf4j
@AllArgsConstructor
public class GatewaySaveLogComponent {

    final GatewayLogService gatewayLogService;

    /**
     * 保存请求日志,@Async 注解所在的类最好不要和调用类放在一个类中,不然有可能无法产生切面
     *
     * @param functionApiCallRecordPo 组装好的日志
     * @author maoxiaomeng
     * @date: 2020/3/31 15:25
     * @return: void
     */
    public void saveLog(GatewayLogPo functionApiCallRecordPo) {
        //有时候这里的数据量巨大,打印很费时间
        log.debug("调用日志结果为,{}", JSONObject.toJSONString(functionApiCallRecordPo));
        //todo 数据保存有问题，不支持特殊符号
        try {
            functionApiCallRecordPo.setId(null);
            gatewayLogService.save(functionApiCallRecordPo);
            log.info("日志存储完成");
        } catch (Exception e) {
            log.error("网关记录日志异常,异常原因:{}", e.getMessage());
            throw new BusinessException("网关记录日志异常,{}", e.getMessage());
        }
    }
}
